package com.iman.manjusri.web;

import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.iman.common.hibernate.HibernateSupport;
import com.iman.common.util.JsonUtil;
import com.iman.common.util.Saltcheckutil;
import com.iman.manjusri.Web7Constants;
import com.iman.manjusri.domain.SessionBean;
import com.iman.manjusri.domain.User;
import com.iman.manjusri.repository.IRedisGo;
import com.iman.manjusri.service.SharedSessionService;
import com.iman.manjusri.service.UserService;
import com.iman.manjusri.util.HoldWebSpringContext;
import com.iman.manjusri.util.Web7Util;

@Controller
@RequestMapping(value = "/login/*")
public class UserLoginController extends BaseController {

	private  Logger logger = LoggerFactory.getLogger(UserLoginController.class);

    @Inject
    UserService userService;

    @Inject
    SharedSessionService sharedSessionService;

    @Inject
    HibernateSupport hibernateSupport;

    @Inject
    IRedisGo redis;

    @Inject
    IndexController  indexController;
    
    
	@RequestMapping(value = "/logout")
	@ResponseBody
	public String logout(User user, HttpServletRequest multipartRequest ,HttpServletResponse response) throws Exception {
		 
		Map<String,String> cookieUid = Web7Util.getUId(multipartRequest );
		logger.info( "session ID  redis key::::>>>"+cookieUid);
		//是redis 中session 过期
		String returnL = this.sharedSessionService.addSessionSaveTimes(cookieUid.get( Web7Constants.SHARECOOKIEUSERID), -1) ;
		
		logger.info( "session ID  redis returnL::::>>>"+returnL);
		 
		
		Web7Util.removeCookie(multipartRequest,response );
		logger.info( "cookie ID  ::::>>>"+cookieUid);
		//就返回  争取的记过  的  json  就完成了
		Map result = new HashMap();
		result.put("code", 1);
        result.put("msg", "退出成功");
        return JsonUtil.toJson(result);
	}
	
	
	@RequestMapping(value = "/new2")
	 
	public ModelAndView login2(User user, HttpServletRequest multipartRequest ,HttpServletResponse response) throws Exception {
		Map  result = this.login(user, multipartRequest, response);
		logger.info( "login2 result::::>>>"+result);
		ModelAndView  mav = null;
		if(result!=null &&  ((Integer)result.get(  "code")) >0 ){
			mav = indexController.homePage(multipartRequest);
			mav.addObject("login", true);
			
			mav.addObject("imgKey", user.getUser_himg());
			mav.addObject("uName", user.getLoginName());
			
			// userType = 5;  用户类型 类型1,系统管理员；2，管理员；3，教师；4，代理商；5，注册用户；
			if(user.getUserType()==1)  {
				
			}else if(user.getUserType()==2)  {
				
			}else if(user.getUserType()==3)  {
				mav.addObject("forward", super.forward_teacher);
			}else if(user.getUserType()==4)  {
				mav.addObject("forward", super.forward_agent);
			}else if(user.getUserType()==5)  {
				mav.addObject("forward", super.forward_student);
			}
			
		}else{
			mav = indexController.homePage(multipartRequest);
		}
		putResourceSrc(  mav);
		return  mav ;
	}
	
	
	@RequestMapping(value = "/new")
	@ResponseBody
	public String login1(User user, HttpServletRequest multipartRequest ,HttpServletResponse response) throws Exception {
		Map result = new  HashMap();
		result = this.login(  user,   multipartRequest ,  response);
		 
        return JsonUtil.toJson(result);
	}
	
	
	@RequestMapping(value = "/agent")
	@ResponseBody
	public String loginAgent(User user, HttpServletRequest multipartRequest ,HttpServletResponse response) throws Exception {
		Map result = new  HashMap();
		result = this.login(  user,   multipartRequest ,  response);
		//判断是否是代理商   ,如果不是代理商直接失败。
		if(user==null || user.getUserType() !=4 ){
			result.put("code",0);
		}
        return JsonUtil.toJson(result);
	}
	
	
	private  Map login(User user, HttpServletRequest multipartRequest ,HttpServletResponse response){

		Map result = new  HashMap();
		
		if (user  == null || user.getLoginName()==null || "".equals(user.getLoginName())) {
		    result.put("code", 0);
            result.put("msg", "账号未注册");
            return  (result);
		}

		// 根据 用户输入的  loginName查询数据库  
		User dbUser = this.userService.getUserByName(user.getLoginName());
		
		if (dbUser  == null) {
		    result.put("code", 0);
            result.put("msg", "账号未注册");
            return  (result);
		}

		if (dbUser.getUserAvtive() == 0) {
		    result.put("code", 0);
            result.put("msg", "账号未激活，请去注册邮箱激活");
            return  (result);
		}    
		// 根据数据库返回的 salt + 用户输入的密码  333进行 加密验证， 然后 和 查询 出来的saltcode对比， 看看是否一样
		String salt = dbUser.getPwdsalt();
		if (!dbUser.getPwd().equals(Saltcheckutil.saltArithmetic(user.getPwd(), salt))) {
		    result.put("code", 0);
            result.put("msg", "密码错误");
            return  (result);
		}
		
		
		  user.setUser_himg( dbUser.getUser_himg() ) ;
		  user.setUserType( dbUser.getUserType());
		  
		//获取session保存  ，并把 这个 ID写到 cookie里面， 起一个名字 叫做 UID。这个ID暂时卸载  *drm.com下， 你配置一个host, drm.com 这个域名是你配置的
		String uid = this.sharedSessionService.putSessionUser(dbUser);
		
		
		logger.info( "session ID  redis key::::>>>"+uid);
		/**
		 * 写入cookie 
		 */
		Web7Util.setUserIdCookie(response,uid);
		logger.info( "cookie ID  ::::>>>"+uid);
		
		
		// userType = 5;  用户类型 类型1,系统管理员；2，管理员；3，教师；4，代理商；5，注册用户；
		if(dbUser.getUserType()==1)  {
			
		}else if(dbUser.getUserType()==2)  {
			
		}else if(dbUser.getUserType()==3)  {
			result.put("forward", super.forward_teacher);
		}else if(dbUser.getUserType()==4)  {
			result.put("forward", super.forward_agent);
		}else if(dbUser.getUserType()==5)  {
			result.put("forward", super.forward_student);
		}
		
		
		//就返回  争取的记过  的  json  就完成了 
		result.put("code", 1);
		result.put("utp", dbUser.getUserType());//用户类型
        result.put("msg", "登录成功");
        return result;
	
	}
	
	
	/**
	 * 验证下载积分
	 * @return
	 */
	@RequestMapping("/getid/{uid}/{uidpk}") 
	@ResponseBody
	public String   getUserId(@PathVariable String uid,@PathVariable String uidpk,HttpServletRequest request){
		
		
		boolean  isRightCookie =   Web7Util.checkCookieIdIsOk(uid,uidpk);
	  	 
		 if(isRightCookie ){
		    	//容器缓存失效
		    	try{
					SharedSessionService sessionUtil =	 	sharedSessionService;
					SessionBean  sessionBean = sessionUtil.getSeesion(uid);
					
					if(sessionBean != null ){
						return  sessionBean.getUser().getUserId().toString();
					}
				}catch(Exception e){
				  logger.error(e.getMessage(),e);
				}
		     }
		
		 
		return "";
	}
	
	
	
}
